In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions which may or may not return a meaningful value when they are applied. It consists of a constructor which either is empty (often named None or Nothing), or which encapsulates the original data type A (often written Just A or Some A).
A distinct, but related concept outside of functional programming, which is popular in object-oriented programming, is called (often expressed as A?). The core difference between option types and nullable types is that option types support nesting (e.g. Maybe (Maybe String) ≠ Maybe String), while nullable types do not (e.g. String?? = String?).
The option type is also a Maybe monad where:
Nothing >>= f = Nothing -- Fails if the previous monad fails
(Just x) >>= f = f x -- Succeeds when both monads succeed
The monadic nature of the option type is useful for efficiently tracking failure and errors.
-- Any constrained & non-limited type.
type Element_Type is private;
package Optional_Type is
-- When the discriminant, Has_Element, is true there is an element field,
-- when it is false, there are no fields (hence the null keyword).
type Optional (Has_Element : Boolean) is record
case Has_Element is
when False => Null;
when True => Element : Element_Type;
end case;
end record;
end Optional_Type;
Example usage:
package Optional_Integers is new Optional_Type
(Element_Type => Integer);
Foo : Optional_Integers.Optional :=
(Has_Element => True, Element => 5);
Bar : Optional_Integers.Optional :=
(Has_Element => False);
| Some(a, true) of a
| None(a, false)
stadef option = option_t0ype_bool_type
typedef Option(a: t@ype) = b:bool option(a, b)
fn show_value (opt: Option int): string =
implement main0 (): void = let
case+ opt of
| None() => "No value"
| Some(s) => tostring_int s
val full = Some 42
and empty = None
in
println!("show_value full → ", show_value full);
println!("show_value empty → ", show_value empty);
end
using std::nullopt; using std::optional;
constexpr optional
void readDivisionResults(int x, int y) {
int main(int argc, char* argv) {
if (y != 0.0) {
return x / y;
}
return nullopt;
}
optional
}
readDivisionResults(1, 5);
readDivisionResults(8, 0);
}
let full = Some 42
let empty = None
showValue full |> printfn "showValue full -> %s"
showValue empty |> printfn "showValue empty -> %s"
Option.fold (fun _ x -> sprintf "The value is: %d" x) "No value"
main :: IO ()
main = do
let full = Just 42
let empty = Nothing
putStrLn $ "showValue full -> " ++ showValue full
putStrLn $ "showValue empty -> " ++ showValue empty
main : IO ()
main = do
let full = Just 42
let empty = Nothing
putStrLn $ "showValue full -> " ++ showValue full
putStrLn $ "showValue empty -> " ++ showValue empty
public class OptionExample {
static String showValue(Optional
public static void main(String[] args) {
Optional
System.out.printf("showValue(full): %s\n", showValue(full));
System.out.printf("showValue(empty): %s\n", showValue(empty));
}
}
proc showValue(opt: Optionint): string =
opt.map(proc (x: int): string = "The value is: " & $x).get("No value")
let
full = some(42)
empty = none(int)
echo "showValue(full) -> ", showValue(full) echo "showValue(empty) -> ", showValue(empty)
let () =
Option.fold ~none:"No value" ~some:(fun x -> "The value is: " ^ string_of_int x)
let full = Some 42 in
let empty = None in
print_endline ("show_value full -> " ^ show_value full);
print_endline ("show_value empty -> " ^ show_value empty)
fn main() {
opt.map_or("No value".to_owned(), |x: i32| format!("The value is: {}", x))
}
let full: Option
println!("show_value(full) -> {}", show_value(full));
println!("show_value(empty) -> {}", show_value(empty));
}
def showValue(opt: Option[Int]): String =
opt.fold("No value")(x => s"The value is: $x")
def main(args: Array[String]): Unit =
val full = Some(42)
val empty = None
println(s"showValue(full) -> ${showValue(full)}")
println(s"showValue(empty) -> ${showValue(empty)}")
let full = 42
let empty: Int? = nil
print("showValue(full) -> \(showValue(full))")
print("showValue(empty) -> \(showValue(empty))")
return opt.map { "The value is: \($0)" } ?? "No value"
}
Payload n can be captured in an if or while statement, such as , and an else clause is evaluated if it is null.
fn showValue(gpa: Allocator, opt: ?i32) !u8 {
pub fn main() !void {
return if (opt) |n|
std.fmt.allocPrint(gpa, "The value is: {}", .{n})
else
gpa.dupe(u8, "No value");
}
// Set up an allocator, and warn if we forget to free any memory.
var debug_allocator: DebugAllocator(.{}) = .init;
defer std.debug.assert(debug_allocator.deinit() == .ok);
const gpa = debug_allocator.allocator();
// Prepare the standard output stream.
var buffer: [1024]u8 = undefined;
var writer = File.stdout().writer(&buffer);
const stdout = &writer.interface;
// Perform our example.
const full = 42;
const empty = null;
const full_msg = try showValue(gpa, full);
defer gpa.free(full_msg);
try stdout.print("showValue(gpa, full) -> {s}\n", .{full_msg});
const empty_msg = try showValue(gpa, empty);
defer gpa.free(empty_msg);
try stdout.print("showValue(gpa, empty) -> {s}\n", .{empty_msg});
try stdout.flush();
}
|
|